<template>
  <div ref="workDeal" id="workDeal" class="wrapper p-3">
    <dialog-bg :height="400"></dialog-bg>
    <!--工单详情-->
    <fieldset class="w-100 mb-2">
      <legend class="w80">工单详情</legend>
      <div class="d-flex">
        <img v-if="!fileURL.length" src="static/image/work.png">
        <el-image v-else style="width: 340px;height: 209px;" :src="fileURL[0]" :preview-src-list="fileURL" ></el-image>
        <div class="pl-3" style="flex: 1;">
          <el-row class="workInfo">
            <el-col :span="8">创建人：<span>{{work.Creator}}</span></el-col>
            <el-col :span="8">工单流水：<span>{{work.No}}</span></el-col>
            <el-col :span="8">工单分类：<span>{{global.WorkTypes[work.Classify]}}</span></el-col>
            <el-col :span="8">工单级别：<span>{{global.WorkLevels[work.Level-1]}}</span></el-col>
            <el-col :span="8">设施编号：<span>{{(work.DevNo&&work.DevNo!=0)?work.DevNo:'无'}}</span></el-col>
            <el-col :span="8">来源信息：
              <span v-for="item in global.FaultSources" v-if="work.Source==item.no">{{item.name}}</span>
            </el-col>
            <el-col :span="8">指派责任区：<span>{{work.AreaName||"测试"}}</span></el-col>
            <el-col :span="8">指派处理人：<span>{{work.AssignedUserName||'admin'}}</span></el-col>
            <el-col :span="8">来电人：<span>{{work.ReportUser||'test'}}</span></el-col>
            <el-col :span="8">工单接收人号码：<span>{{work.SmsPhone||''}}</span></el-col>
            <el-col :span="8">开始时间：<span>{{work.StartTime}}</span></el-col>
            <el-col :span="8">结束时间：<span>{{work.EndTime}}</span></el-col>
            <el-col :span="24">工单内容：<span>{{work.Content}}</span></el-col>
          </el-row>
        </div>
      </div>
    </fieldset>
    <!--工单操作/回执-->
    <el-row  :gutter="15" >
      <el-col :span="12">
        <fieldset class="w-100">
          <legend class="w100"> <i class="iconfont icon-biaotizhongdian font18"></i>工单过程</legend>
          <el-table  class="ur-table" stripe ref="tableDom1" :data="tables.datas" :height="300" highlight-current-row >
            <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="50"></el-table-column>
            <el-table-column v-for="(v,index) in tables.columns" :prop="v.field" :label="v.title" :width="v.width" align="center" :key="index">
              <template slot-scope="scope">
                <span v-if="v.field=='WorkOrderState'">{{global.WorkResults[scope.row[v.field]]}}</span>
                <span v-else>{{scope.row[v.field]}}</span>
              </template>
            </el-table-column>
          </el-table>
        </fieldset>
      </el-col>
      <el-col :span="12">
        <fieldset class="w-100">
          <legend class="w100"> <i class="iconfont icon-biaotizhongdian font18"></i>回执信息</legend>
          <!--回执信息-->
          <receipt-list :page="page"  :workResult="workResult" :receipts="receipts"  @receiptDialog="receiptDialog"></receipt-list>
        </fieldset>
      </el-col>
    </el-row>

   <!--审核{0：'待指派':1：'待处理',:2：处理中':3：'已处理',4：'申请延期','',6：'无法处理',
   7：'非我所':8：'非我组','',10：'已修复（工单结束）':11：'无法处理（工单结束）'},-->
<!--    待指派page!='history'&&-->
    <div class="p_relative" v-if="![10,11].includes(workResult)">
      <el-form class="ur-form mt-3" :inline="true" >
        <template v-if="[1,2,8].indexOf(workResult)!=-1&&RoleType==1">
          <el-form-item class="mb-2 ml-1" label="处理结果" >
            <el-select class="w140" size="small"  v-model="result" >
              <el-option label="已处理" :value="3"></el-option>
              <el-option label="申请延期" :value="4"></el-option>
              <el-option label="无法处理" :value="6"></el-option>
              <el-option label="非我所" :value="7"></el-option>
              <el-option label="非我组" :value="8"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="mb-2" label="处理说明" >
            <el-input :disabled="result==8" :class="{'w220':result==8,'w400':result!=8}" size="small" v-model="content"></el-input>
          </el-form-item>
        </template>
        <template v-if="([0,8].indexOf(workResult)!=-1||result==8)">
          <el-form-item class="mb-2" label="指派责任区" >
            <el-select :disabled="result==8" class="w130" size="small"  v-model="assignedAreaId" @change="getUsers">
              <el-option label="请选择" :value="0"></el-option>
              <el-option v-for="(item,index) in areas" :key="index" :label="item.Name" :value="item.Id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="mb-2" label="指派处理人" >
            <el-select class="w130" size="small" v-model="assignedUserId" @change="selUser">
              <el-option label="请选择" :value="0"></el-option>
              <el-option v-for="(item,index) in users" :key="index+1" :label="item.Name" :value="item.Id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="mb-2 mr-0" label="工单接收人号码" >
            <el-input class="w150" size="small" v-model="smsPhone"></el-input>
          </el-form-item>
        </template>
        <template v-if="workResult==4&&RoleType==0">
          <el-form-item class="mb-2" label="延期日期" >
            <el-date-picker type="date" v-model="delayTime"  class="w-100" size="small"></el-date-picker>
          </el-form-item>
        </template>
        <template v-if="[3,4,6,7].indexOf(workResult)!=-1&&RoleType==0">
          <el-form-item class="mb-2" label="审核说明" >
            <el-input class="w400" size="small" v-model="checkContent"></el-input>
          </el-form-item>
        </template>

        <template v-if="[3,4,6,7].indexOf(workResult)!=-1&&RoleType==0">
          <el-button class="ur-btn ur-btn-primary" @click="check(0)"><i class="iconfont icon-sure"></i>通过</el-button>
          <el-button class="ur-btn ur-btn-primary" @click="check(1)"><i class="iconfont icon-close3"></i>不通过</el-button>
        </template>
        <!--审核中 养护单位提示-->
        <el-alert  show-icon title="正在审核中..." type="warning"  :closable="false" v-if="[3,4,6].indexOf(workResult)!=-1&&RoleType==1"></el-alert>
      </el-form>
      <div class="text-center">
        <template v-if="btnState()">
          <el-button class="ur-btn ur-btn-primary mt-3" @click="deal"><i class="iconfont icon-sure"></i>确定</el-button>
          <el-button class="ur-btn ur-btn-primary mt-3" @click="close"><i class="iconfont icon-close3"></i>取消</el-button>
        </template>

      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import workAdd from './work-add'
  import receiptList from './receipt-list'
  import fileRead from "base/fileRead/fileRead2"
  import dialogBg from "base/dialog-bg"
  import elDragDialog from 'directive/el-dragDialog'
  import {mapState} from 'vuex'
  import api from 'api/api'
  import fetch from 'api/fetch'

  export default {
    directives:{elDragDialog},
    components: {workAdd,receiptList,fileRead,dialogBg},
    props: {
      work:null,
      page:''
    },
    data() {
      return {
        result:3,
        tables: {
          sel: null,//选中行
          columns: [
              //控制箱、RTU单灯
              {field: "WorkOrderState", title: "处理结果", width: '120'},
              {field: "Processor", title: "处理人", width: null},
              {field: "Content", title: "处理说明", width: null},
              {field: "Created", title: "处理时间", width: 160},
          ],
          datas: []
        },
        workResult:null,
        showReceipt:false,
        receipts:[],
        users:[],
        areas:[],
        assignedAreaId:null,
        assignedUserId:0,
        content:'',
        checkContent:'',
        server:api.ajaxServe,
        height:0,
        files:[],
        showCarousel:false,
        delayTime:api.formatDate(new Date()),
        smsPhone:'',
        fileURL:[]
      }
    },
    watch: {
      result(v){
        if(v==8){
          this.btnState(8)
        }
      }
    },
    computed: {
      ...mapState({

        RoleType:state=>state.user.userInfo.RoleType,
        limits:state=>state.user.userInfo.limits
      })
    },
    methods: {
      closeFileRead(v){
        this.showCarousel=false
      },
      selUser(userId){
        if(this.workResult==7){//非我所
          this.validateAreaId(this.assignedUserId,'assignedUserId','请选择')
        }
        this.users.map(r=>{
          if(r.Id==userId){
            this.smsPhone=r.Mobile
          }
        })
      },
      indexMethod(index) {
        return index + 1
      },
      //按钮状态 显示 不显示
      btnState(state){
        //{0：'待指派':1：'待处理',:2：处理中':3：'已处理',4：'申请延期','',6：'无法处理',7：'非我所':8：'非我组','',10：'已修复（工单结束）':11：'无法处理（工单结束）'}
        if(state==3){
        }else if(state==8){//,7
          return (this.RoleType==0&&[0].indexOf(this.workResult)==-1)||(this.RoleType==1&&this.result!=8)
        }else{
          //((this.workResult==0&&this.assignedUserId!=null)||this.workResult==7) ,7
          return ([0].indexOf(this.workResult)!=-1&&this.RoleType==0)||([1,2,8].indexOf(this.workResult)!=-1&&this.RoleType==1)
        }
      },
      receiptDialog(v){
        this.$emit('receiptDialog',{showWorkDeal:false,showReceipt:true,isAdd:v.isAdd,receipt:v.receipt})
      },
      queryWorkById() {
        api.fetchSimple('/SHWorkorder/QueryWorkDetail?worderId=' + this.work.Id, {})
          .then(r => {
            this.receipts = r.receipt
            this.tables.datas = r.his
            this.files = r.files ? r.files : []
            this.height = this.$refs.workDeal.clientHeight //图片预览的高度
            if(this.files.length==0) return
            for(let i=0;i<this.files.length;i++){
              this.fileURL.push(api.ajaxServe+this.files[i].OriginUrl)
            }
          })
      },
      queryArea(){
        api.fetchSimple('/ViewInfo/QueryRegionsForTree').then(r=>{
          this.getAllRegion(r)
        })
      },
      getAllRegion(areas){
        if(areas.length==0) return
        areas.map(o=>{
          this.areas.push(o);
          if(o.Childs.length){
            this.getAllRegion(o.Childs)
          }
        })
      },
      validateAreaId(value,name,msg){
        if (value == 0) {
          if (this.$validator.errors.has(name)) {
            this.$validator.errors.remove(name)
          }
          this.$validator.errors.add({
            field: name,
            msg: msg
          })
          return false
        } else {
          this.$validator.errors.remove(name)
          return true
        }
      },
      getUsers(){
        this.validateAreaId(this.assignedAreaId,'assignedAreaId','请选择责任区')
        api.fetchSimple('/User/QueryByRegions',{regionId:this.assignedAreaId})
          .then(r=>{
            this.users=r
            if(this.workResult!=7){//0待指派 8非我所显示指派人
              this.assignedUserId=this.work.AssignedUserId?this.work.AssignedUserId:this.users[0].Id
              this.smsPhone=this.work.SmsPhone?this.work.SmsPhone:this.users[0].Mobile
            }
          })
      },
      delFile(file,index){//删除工单附件
        this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
          .then(() => {
            api.fetchSimple('/SHWorkorder/DelWorkFiles',{workId:this.work.Id,fileIds:[file.Id]})
              .then(r=>{
                this.files.splice(index,1)
                if(this.files.length==0) this.showCarousel=false
              })
          })
      },
     //工单处理
      deal(){
        let res=this.validateAreaId(this.assignedAreaId,'assignedAreaId','请选择责任区')
        let res2=true
        if(this.workResult==7){
          res2=this.validateAreaId(this.assignedUserId,'assignedUserId','请选择')
        }
        if(!res||!res2) return
        let fetch_res=''
        if(this.result){ //养护单位处理
          // if(this.limits.indexOf('3_01_01_08')==-1) return this.$message.error({showClose:true,message:'该用户无权限操作'})
          fetch_res=api.fetchSimple('/SHWorkorder/SaveProcessResult',{workId:this.work.Id,state:this.result,pContent:this.content,assignUserId:this.assignedUserId,tels:this.smsPhone})
        }
        if([0,7].indexOf(this.workResult)!=-1){ //公用署 指派责任区、指派处理人
       //   if(this.limits.indexOf('3_01_01_09')==-1) return this.$message.error({showClose:true,message:'该用户无权限操作'})
          fetch_res=api.fetchSimple('/SHWorkorder/SaveAssignResult',{workId:this.work.Id,areaId:this.assignedAreaId,userId:this.assignedUserId,tels:this.smsPhone})
        }
        fetch_res.then(r=>{
            this.close()
          })
      },
      //审核
      check(isPass){
        let data={workId:this.work.Id,content:this.checkContent,isPass:isPass}
        if(this.workResult==4){
          data=Object.assign(data,{delayTime:this.delayTime})
        }
        api.fetchSimple('/SHWorkorder/SaveAuditResult',data).then(r=>{
          this.close()
        })
      },
      close(){
        this.$emit('receiptDialog',{showWorkDeal:false,showReceipt:false,isAdd:false,receipt:null})
      }
    },
    created() {
      this.workResult=this.work.WorkOrderState
      this.assignedAreaId=this.work.AssignedAreaId
      if(this.work.AssignedAreaId!=0) this.getUsers()
      this.queryArea()
    },
    mounted() {
      this.queryWorkById()
    }
  }
</script>
<style  lang="stylus" rel="stylesheet/stylus">
  #workDeal{
    .workInfo{
      .el-col{
        font-size:16px;line-height:30px;
        span{color:#44FF95;}
      }
    }
  }
</style>
